<script setup>
import {onMounted, ref} from "vue";
import {useUserStore} from "@/stores/index.js";
import {ElMessage} from "element-plus";
import axios from "axios";
import {orderBatchRemove, orderGetListService, orderUpdateService} from "@/api/modules/order.js";

defineOptions({name: 'orderManagement'})
const queryParams = ref({
  page: 1,
  size: 5,
  key: ''
})
const tableModel = ref([])
const total = ref(0)
const getOrderList = async () => {
  const {page, size, key} = queryParams.value
  const res = await orderGetListService(page, size, key)
  tableModel.value = res.records
  total.value = res.total
}

const handleSizeChange = async (event) => {
  queryParams.value.size = event
  await getOrderList()
}

const handlePageChange = async (event) => {
  queryParams.value.page = event
  await getOrderList()
}

const handleKeyChange = async (event) => {
  queryParams.value.key = event
}

const handleSearch = async () => {
  await getOrderList()
}
onMounted(async () => {
  await getOrderList()
})

const selectionIds = ref([])
const selectionChange = (event) => {
  selectionIds.value = event.map(item => item.id)
}
const batchRemove = async () => {
  await orderBatchRemove(selectionIds.value);
  await getOrderList()
}

const updateOrderStatus = async (id, status) => {
  await orderUpdateService({id: id, orderStatus: status})
  await getOrderList()
}

const showDetails = ref(false)
const detailModel = ref({})
const handleDetails = (row) => {
  showDetails.value = true
  detailModel.value = row
}

const closeDetail = () => {
  detailModel.value = {}
}

const baseUrl = import.meta.env.VITE_APP_BASE_API
const userStore = useUserStore()
const exportExcel = async () => {
  if (selectionIds.value.length === 0) {
    ElMessage.error('请勾选要导出的数据~')
    return
  }
  // 发送HTTP GET请求获取Excel文件流
  axios({
    url: `${baseUrl}/admin/order/export`,
    method: 'POST',
    responseType: 'blob', // 重要
    data: selectionIds.value,
    headers: {
      'Authorization': userStore.token // 如果需要token，添加到请求头中
    }
  }).then((response) => {
    // 创建一个Blob对象，内容为后端返回的文件流
    const blob = new Blob([response.data], {type: 'application/vnd.ms-excel'});

    // 创建一个a标签，用于触发下载
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = '订单表.xlsx'; // 下载文件的名称
    link.click();

    // 清理资源
    URL.revokeObjectURL(link.href);
  }).catch((error) => {
    console.error('下载失败:', error);
  });
}
</script>

<template>
    <!--    订单详情-->
    <el-drawer direction="ttb" size="100%" v-model="showDetails" @close="closeDetail">
      <template #header>
        <h3 style="text-align: center">订单详情</h3>
      </template>
      <template #default>
        <div class="content"></div>
        <el-form disabled label-position="right" label-width="300">
          <el-form-item label="订单编号">
            <el-input :value="detailModel.id"/>
          </el-form-item>
          <el-form-item label="搬货车型">
            <el-input :value="detailModel.carTypeName"/>
          </el-form-item>
          <el-form-item label="搬运起始地址">
            <el-input :value="detailModel.srcFullAddress"/>
          </el-form-item>
          <el-form-item label="搬运目的地址">
            <el-input :value="detailModel.descFullAddress"/>
          </el-form-item>
          <el-form-item label="起始地址搬运方式">
            <el-input :value="detailModel.srcMoveWay === 0 ? '全程电梯' : '楼梯：' + detailModel.srcFloorLevel + '楼'"/>
          </el-form-item>
          <el-form-item label="目的地址搬运方式">
            <el-input
                :value="detailModel.descMoveWay === 0 ? '全程电梯' : '楼梯：' + detailModel.descFloorLevel + '楼'"/>
          </el-form-item>
          <el-form-item label="搬运时间">
            <el-input :value="detailModel.moveTime"/>
          </el-form-item>
          <el-form-item label="大件物品数量">
            <el-input :value="detailModel.bigGoodsCount"/>
          </el-form-item>
          <el-form-item label="是否需要司机协助搬运">
            <el-input :value="detailModel.needHelp === 1 ? '是' : '否'"/>
          </el-form-item>
          <el-form-item label="订单状态">
            <el-input :value="detailModel.orderStatus===1?'待搬运':(detailModel.orderStatus===2?'搬运中':'已完成')"/>
          </el-form-item>
          <el-form-item label="支付方式">
            <el-input :value="detailModel.payType === 1 ? '微信支付' : '银行卡支付'"/>
          </el-form-item>
          <el-form-item label="运输费用">
            <el-input :value="detailModel.transportPrice + '元'"/>
          </el-form-item>
          <el-form-item label="搬运费用">
            <el-input :value="detailModel.carryPrice + '元'"/>
          </el-form-item>
          <el-form-item label="总费用">
            <el-input :value="detailModel.transportPrice + detailModel.carryPrice + '元'"/>
          </el-form-item>
          <el-form-item label="联系方式">
            <el-input :value="detailModel.phone"/>
          </el-form-item>
          <el-form-item label="订单备注">
            <el-input :value="detailModel.remark" type="textarea" autosize/>
          </el-form-item>
        </el-form>
      </template>
    </el-drawer>
    <el-card>
      <template #header>
        <div class="header">
          <div class="left">
            <el-button type="danger" @click="batchRemove" v-hasPerm="'biz:order:dml'">删除勾选</el-button>
            <el-button type="primary" class="export" @click="exportExcel" v-hasPerm="'biz:order:export'">导出Excel
            </el-button>
          </div>
          <div class="right">
            <el-input @input="handleKeyChange" @keyup.enter="handleSearch" prefix-icon="Search"
                      v-model="queryParams.key" class="input" placeholder="输入订单编号" clearable
                      v-hasPerm="'biz:order:dql'"></el-input>
            <el-button type="primary" @click="handleSearch" class="search" v-hasPerm="'biz:order:dql'">查询
            </el-button>
          </div>
        </div>
      </template>
      <el-table :data="tableModel" @selection-change="selectionChange" row-key="id">
        <el-table-column type="selection" reserve-selection show-overflow-tooltip/>
        <el-table-column prop="id" label="订单编号" width="200">
          <template #default="{row}">
            <el-link :underline="false" @click="handleDetails(row)">
              {{ row.id }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="联系方式" width="140"/>
        <el-table-column prop="moveTime" label="搬运时间"/>
        <el-table-column prop="orderStatus" label="订单状态">
          <template #default="{row}">
            <span v-if="row.orderStatus===1">待搬货</span>
            <span v-if="row.orderStatus===2">搬货中</span>
            <span v-if="row.orderStatus===3">已完成</span>
            <span v-if="row.orderStatus===4">已完成</span>
          </template>
        </el-table-column>
        <el-table-column label="订单处理" v-hasPerm="'biz:order:dml'">
          <template #default="{row}">
            <el-button v-if="row.orderStatus===1" @click="updateOrderStatus(row.id,2)"
                       type="primary">
              去搬货
            </el-button>
            <el-button v-if="row.orderStatus===2" @click="updateOrderStatus(row.id,3)"
                       type="success">完成订单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.size"
          :page-sizes="[5,10,15,20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
      />
    </el-card>
</template>


<style lang="scss" scoped>
.el-card {
  padding: 0;
  height: 100%;

  :deep .el-card__header {
    height: 50px;
    padding: 10px;
  }

  :deep .el-card__body {
    height: calc(100% - 120px);
    padding: 10px;
  }
  :deep .el-card__footer {
    height: 50px;
    padding: 10px;
  }
  .el-table {
    height: calc(100%);
  }
}


.avatar {
  height: 50px;
  border-radius: 50%;
}

.header {
  display: flex;
  justify-content: space-between;

  .right {
    .search {
      margin: 0 10px;
    }
  }

  .input {
    width: 150px;
  }
}


.el-input {
  width: 700px;
}
</style>
